package com.vichat.business.controller;

import com.vichat.business.entity.VcAlarm;
import com.vichat.business.service.IVcAlarmService;
import com.vichat.business.thread.AlarmSendThread;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.service.IRoomService;
import com.vichat.room.vo.RoomVO;
import com.vichat.user.controller.BaseController;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/vcapi/alarm")
public class AlarmController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AlarmController.class);

    ExecutorService tp = Executors.newCachedThreadPool();

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private IVcAlarmService vcAlarmService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoomService roomService;

    /**
     * 创建告警
     *
     * @return
     */
    @RequestMapping("/alarm")
    @ResponseBody
    public Json alarm(@RequestBody VcAlarm vcAlarm) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();

            VcAlarm queryBean = null;
            if (NumberUtils.isNotNullOrZero(vcAlarm.getAlarmId())) {
                queryBean = vcAlarmService.getAlarmByalarmId(vcAlarm.getAlarmId(), 1L);
            } else if (NumberUtils.isNotNullOrZero(vcAlarm.getUid())) {
                queryBean = vcAlarmService.getAlarmByUid(vcAlarm.getUid(), 1L);
            }

            if (queryBean == null) {
                List<UserBasic> userBasicListFDB = userService.getUserBasicsByOrgId(sessionUser.getOrgId());
                //创建临时频道
                RoomBasic roomBasic = createRoom(userBasicListFDB, sessionUser, vcAlarm);
                //创建告警
                VcAlarm alarm = vcAlarmService.saveAlarm(convertAlarm(roomBasic, vcAlarm));

                tp.execute(new AlarmSendThread(roomService, roomBasic.getRid(), GlobalConstant.IMS_ALARM, alarm));
            } else {
                if (StringUtils.isNotBlank(vcAlarm.getLongitude()) && StringUtils.isNotBlank(vcAlarm.getLatitude()) && vcAlarm.getLocTime() > queryBean.getLocTime()) {
                    queryBean.setLongitude(vcAlarm.getLongitude());
                    queryBean.setLatitude(vcAlarm.getLatitude());
                    queryBean.setAddress(vcAlarm.getAddress());
                    queryBean.setPreCision(vcAlarm.getPreCision());
                    queryBean.setLocType(vcAlarm.getLocType());
                    queryBean.setLocTime(vcAlarm.getLocTime());
                    queryBean.setAlarmType(vcAlarm.getAlarmType());
                    queryBean = vcAlarmService.saveAlarm(queryBean);
                }
            }
            json.setObj(queryBean);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    private VcAlarm convertAlarm(RoomBasic roomBasic, VcAlarm vcAlarm) throws Exception {
        vcAlarm.setPartyId(roomBasic.getPartyId());
        vcAlarm.setOrgCode(roomBasic.getOrgCode());
        vcAlarm.setOrgId(roomBasic.getOrgId());
        vcAlarm.setRid(roomBasic.getRid());
        vcAlarm.setAlarmType(1L);
        vcAlarm.setAlarmState(1L);
        vcAlarm.setState(1L);
        return vcAlarm;
    }


    private RoomBasic createRoom(List<UserBasic> userBasicListFDB, UserBasic userBasicFDB, VcAlarm alarmVO) throws Exception {
        RoomVO roomVO = new RoomVO();
        roomVO.setPartyId(userBasicFDB.getPartyId());
        roomVO.setOrgId(userBasicFDB.getOrgId());
        roomVO.setOrgCode(userBasicFDB.getOrgCode());
        roomVO.setUid(userBasicFDB.getUid());
        roomVO.setName(alarmVO.getRoomName());
        roomVO.setUids(getUidsList(userBasicListFDB));
        if (NumberUtils.isNullOrZero(alarmVO.getRoomStyle())) {
            roomVO.setStyle(90L);
        } else {
            roomVO.setStyle(alarmVO.getRoomStyle());
        }
        roomVO.setExpireType(1L);
        RoomBasic roomBasicFDB = roomService.createRoom2Member(roomVO);
        if (roomBasicFDB != null) {
            roomService.updateRoomBasicVersion(roomBasicFDB.getRid());

            if (!roomVO.getUids().isEmpty() && roomBasicFDB != null) {
                for (long uid : roomVO.getUids()) {
                    roomService.updateRoomMemberVersion(uid,roomBasicFDB.getRid());
                }
            }
        }
        return roomBasicFDB;
    }

    private List<Long> getUidsList(List<UserBasic> userBasicListFDB) {
        List<Long> uids = new ArrayList<>();
        for (UserBasic userBasic : userBasicListFDB) {
            uids.add(userBasic.getUid());
        }
        return uids;
    }

    /**
     * 查询告警信息
     *
     * @return
     */
    @RequestMapping("/queryAlarm")
    @ResponseBody
    public Grid queryVcAlarm(@RequestBody VcAlarm queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            UserBasic userBasic = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                throw new Exception("partyId不能为空");
            }
            if (queryBean.getPartyId().longValue() == userBasic.getPartyId().longValue()) {
                List<VcAlarm> vcAlarmFDB = vcAlarmService.queryAlarms(queryBean, pf);

                if (vcAlarmFDB != null && !vcAlarmFDB.isEmpty()) {
                    for (VcAlarm alarm : vcAlarmFDB) {
                        String uName = RedisHelper.getUname(alarm.getUid());
                        alarm.setuName(uName);
                        if (NumberUtils.isNotNullOrZero(alarm.getDealUid())) {
                            UserBasic userBasicFDB = userService.getUserBasicByUid(alarm.getDealUid());
                            if (userBasicFDB != null) {
                                alarm.setDealUName(userBasicFDB.getUserName());
                            }
                        }
                    }
                }
                Long count = vcAlarmService.countAlarms(queryBean);
                grid.setData(vcAlarmFDB);
                grid.setCount(count);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 关闭告警
     *
     * @return
     */
    @RequestMapping("/finishAlarm")
    @ResponseBody
    public Json finishAlarm(VcAlarm queryBean) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                throw new Exception("partyId不能为空");
            }
            if (queryBean.getPartyId().longValue() == userBasic.getPartyId().longValue()) {

                VcAlarm queryBeanFDB = null;
                if (NumberUtils.isNotNullOrZero(queryBean.getAlarmId())) {
                    queryBeanFDB = vcAlarmService.getAlarmByalarmId(queryBean.getAlarmId(), 0L);
                } else if (NumberUtils.isNotNullOrZero(userBasic.getUid())) {
                    queryBeanFDB = vcAlarmService.getAlarmByUid(userBasic.getUid(), 0L);
                }

                if (queryBeanFDB != null) {
                    //关闭告警
                    queryBeanFDB.setAlarmState(queryBean.getAlarmState());
                    queryBeanFDB.setDealTime(new Date());
                    queryBeanFDB.setDealUid(userBasic.getUid());
                    VcAlarm alarm = vcAlarmService.saveAlarm(queryBeanFDB);

                    tp.execute(new AlarmSendThread(roomService, alarm.getRid(), GlobalConstant.IMS_ALARM_CLOSE, alarm));

                    //删除告警频道
                    RoomBasic roomBasic = roomService.getRoomBasicByRid(queryBeanFDB.getRid());
                    if (roomBasic != null) {
                        roomService.delRoomBasic(queryBeanFDB.getRid());
                        roomService.updateRoomBasicVersion(queryBeanFDB.getRid());
                    }
                }
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 处理告警
     *
     * @return
     */
    @RequestMapping("/dealAlarm")
    @ResponseBody
    public Json dealAlarm(VcAlarm queryBean) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                throw new Exception("partyId不能为空");
            }
            if (queryBean.getPartyId().longValue() == userBasic.getPartyId().longValue()) {

                VcAlarm queryBeanFDB = null;
                if (NumberUtils.isNotNullOrZero(queryBean.getAlarmId())) {
                    queryBeanFDB = vcAlarmService.getAlarmByalarmId(queryBean.getAlarmId(), 1L);
                } else if (NumberUtils.isNotNullOrZero(userBasic.getUid())) {
                    queryBeanFDB = vcAlarmService.getAlarmByUid(userBasic.getUid(), 1L);
                }

                if (queryBeanFDB != null) {
                    //开始处理告警
                    queryBeanFDB.setAlarmState(queryBean.getAlarmState());
                    queryBeanFDB.setDealTime(new Date());
                    queryBeanFDB.setDealUid(userBasic.getUid());
                    VcAlarm alarm = vcAlarmService.saveAlarm(queryBeanFDB);

                    tp.execute(new AlarmSendThread(roomService, alarm.getRid(), GlobalConstant.IMS_ALARM_OPEN, alarm));
                }
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 保存
     *
     * @return
     */
    @RequestMapping("/saveDealResult")
    @ResponseBody
    public Json saveDealResult(Long alarmId, String dealResult) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            VcAlarm vcAlarm = vcAlarmService.getAlarmByalarmId(alarmId);
            if (userBasic.getPartyId().longValue() == vcAlarm.getPartyId().longValue()) {
                vcAlarmService.saveDealResult(alarmId, dealResult);
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }
}
